package com.ruoyi.mqtt.callback;


import com.ruoyi.mqtt.client.MyMqttClient;
import com.ruoyi.mqtt.config.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/***
 * Mqtt 消息返回指定接口
 * 第一家中继器厂家信息接收类
 * @author 0000
 */
@Slf4j
@Component
public class DefaultCallback implements MqttCallbackExtended {
    private static final Logger logger = LoggerFactory.getLogger(DefaultCallback.class);

    @Autowired
    private MyMqttClient client;

    @Autowired
    private MqttConfig mqttConfig;

    /**
     * 断开连接的回调
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        new Thread(() -> {
            logger.info("[MQTT] 连接断开，1s之后尝试重连...", throwable);
            boolean reconnecting = false;
            for (int i = 1; i < 5; i++) {
                try {
                    if (client.getClient().isConnected()) {
                        break;
                    }
                    Thread.sleep(1000);
                    boolean needReconnect = !mqttConfig.isAutomaticReconnection() && !reconnecting && !client.getClient().isConnected();
                    if (needReconnect) {
                        logger.info("开始重连...");
                        client.getClient().reconnect();
                        reconnecting = true;
                    }
                } catch (Exception e) {
                    logger.info("mqtt重连失败,继续重连,reason:" + e.getMessage(), e);
                    continue;
                }
            }
        }).start();
    }

    /**
     * 接收消息的地方/响应
     *
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("=====接收消息主题 : " + topic);
        String msg = new String(mqttMessage.getPayload());
        log.info("=====接收消息内容 : " + msg);
        String[] tsplit = topic.split("/");
    }

    /**
     * 消息发送成功后的回调
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("=====deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    /**
     * 连接成功的回调
     *
     * @param b
     * @param s
     */
    @Override
    public void connectComplete(boolean b, String s) {
        // 订阅 topic
        client.subscribe("$cn/lrwjz/#", 0);
        log.info("mqtt连接成功，客户端ID：" + mqttConfig.getUrls());
    }

}
